package com.zhihaoliang.coroutine.buss.flow.func

import com.zhihaoliang.coroutine.util.log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import kotlin.coroutines.coroutineContext

/**
 * @author 支豪亮
 * @date 2022/10/24 11:27
 * @des Flows are cold。 Flow does not run until the flow is collected.
 */
object FlowCold {
    fun onFlowCold(mainScope: CoroutineScope) = mainScope.launch {
        log("Calling simple function...",coroutineContext)
        val flow = simple()
        log("Calling collect...",coroutineContext)
        flow.collect { value -> log(value,coroutineContext) }
        log("Calling collect again...",coroutineContext)
        flow.collect { value -> log(value,coroutineContext)}
    }

    private fun simple(): Flow<Int> = flow {
        log("Flow started",coroutineContext)
        for (i in 1..3) {
            delay(100)
            emit(i)
        }
    }

}